package com.maduar.batch.job;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.flow.JobExecutionDecider;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.maduar.batch.constant.JobConstant.EVEN;
import static com.maduar.batch.constant.JobConstant.ODD;

/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @date 2021-07-10 14:18
 */
@Slf4j
@Configuration
@EnableBatchProcessing
public class DeciderJob {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    private String jobName = "deciderJob";
    private String step1 = "deciderJob-step1";
    private String step2 = "deciderJob-step2";
    private String step3 = "deciderJob-step3";

    @Bean
    public Step deciderStep1() {
        return stepBuilderFactory.get(step1)
                .tasklet((stepContribution, chunkContext) -> {
                    log.info(EVEN);
                    return RepeatStatus.FINISHED;
                })
                .build();
    }

    @Bean
    public Step deciderStep2() {
        return stepBuilderFactory.get(step2)
                .tasklet((stepContribution, chunkContext) -> {
                    log.info(EVEN);
                    return RepeatStatus.FINISHED;
                })
                .build();
    }

    @Bean
    public Step deciderStep3() {
        return stepBuilderFactory.get(step3)
                .tasklet((stepContribution, chunkContext) -> {
                    log.info(ODD);
                    return RepeatStatus.FINISHED;
                })
                .build();
    }

    @Bean
    public JobExecutionDecider myDecider() {
        return new MyDecider();
    }

    @Bean
    public Job myDeciderJob() {
        return jobBuilderFactory.get(jobName)
                .start(deciderStep1())
                .next(myDecider())
                .from(myDecider()).on(EVEN).to(deciderStep2())
                .from(myDecider()).on(ODD).to(deciderStep3())
                .from(deciderStep3()).on("*").to(myDecider())
                .end()
                .build();
    }
}
